﻿using AuthCenter.Common;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.login;
using B.S.BasicData.Read.DTOS;
using MediatR;


namespace B.S.BasicData.Read.Apilication.Handler.login
{
    public class GetloginHandler : IRequestHandler<GetloginCommon, ApiResult<UserDTO>>
    {
        private readonly IBaseRepository<UserModel> userRepo;
        private readonly IBaseRepository<AccountRoleModel> accountroleRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<DepartmentModel> deparmentRepo;
        private readonly JwtTools jwtTools;
        private readonly IConfiguration configuration;

        public GetloginHandler(IBaseRepository<UserModel> userRepo,IBaseRepository<AccountRoleModel> accountroleRepo,IBaseRepository<RoleModel> roleRepo,IBaseRepository<DepartmentModel> deparmentRepo, JwtTools jwtTools, IConfiguration configuration)
        {
            this.userRepo = userRepo;
            this.accountroleRepo = accountroleRepo;
            this.roleRepo = roleRepo;
            this.deparmentRepo = deparmentRepo;
            this.jwtTools = jwtTools;
            this.configuration = configuration;
        }
        public Task<ApiResult<UserDTO>> Handle(GetloginCommon request, CancellationToken cancellationToken)
        {
            ApiResult<UserDTO> res = new ApiResult<UserDTO>();
            var account = userRepo.GetAll().Where(x=>x.UserName==request.UserName).FirstOrDefault();
            if (account == null)
            {
                res.Code=ApiEnum.Error;
                res.Message = "用户名不存在";
                return Task.FromResult(res);
                
            }
            if(account.PassWord!=request.PassWord)
            {
                res.Code = ApiEnum.Error;
                res.Message = "密码错误";
                return Task.FromResult(res);
            }

            var accountrole = accountroleRepo.GetAll().Where(x => x.UserId == account.UserId).FirstOrDefault();
            var role = roleRepo.GetValue(accountrole.RoleId).Result;
            var delpaemntid= deparmentRepo.GetValue(account.DepartmentID).Result;


            UserDTO userDTO = new UserDTO()
            {
                UserId = account.UserId,
                UserName = account.UserName,
                PassWord = account.PassWord,
                DepartmentId = delpaemntid.DepartmentId,
                RoleId = accountrole.RoleId,
                RoleName = role.RoleName,
                token = jwtTools.JwtNewString(configuration,account.UserId.ToString())
            };

            res.Code = ApiEnum.Success;
             res.Message = "登录成功";
            res.Data=userDTO;
            return Task.FromResult(res);

        }
    }
}
